import { Schema, model, models, Model, Types } from 'mongoose';
import { ICategory } from '@/types/schema';

/**
 * 全部分类
 */
export const allCategoryItem = {
  _id: '',
  cateName: '全部分类',
  alias: '',
  img:
    '',
  sequence: -1
};

/**
 * 未分类
 */
export const otherCategoryItem = {
  _id: new Types.ObjectId('5dc52b0aba304f6314a9229f'),
  cateName: '未分类',
  alias: 'others',
  img:
    '',
  sequence: 10001
};

export class Category {
    private _model: Model<ICategory>;

    constructor () {
      const schema = new Schema<ICategory>(
        {
          // 分类名称
          cateName: { type: String },

          // 分类别名
          alias: { type: String },

          // 图标地址
          img: { type: String },

          // 排序
          sequence: { type: Number },

          // 创建时间
          createTime: { type: Date, default: new Date() },

          // 修改时间
          modifyTime: { type: Date, default: new Date() }
        },
        {
          // 设置查询时默认返回虚拟字段
          toJSON: { virtuals: true },
          toObject: { virtuals: true }
        }
      );

      // 初始化未分类
      schema.statics.initData = () => {
        this.model.exists({}).then(exist => {
          if (!exist) {
            this.model.create(otherCategoryItem);
          }
        });
      };

      if (models.category) {
        this._model = models.category;
      } else {
        this._model = model<ICategory>('category', schema, 'category');
      }
    }

    public get model (): Model<ICategory> {
      return this._model;
    }
}
